package com.gzy.wb.server;

import com.gzy.wb.controller.para.UserCreatePara;
import com.gzy.wb.core.R;
import com.gzy.wb.exception.AppException;
import com.gzy.wb.model.User;
import com.gzy.wb.repository.UserRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;

@Service
public class AuthServer {

    @Autowired
    UserRepository userRepository;


    @Autowired
    UserServer userServer;

    public String login(String username, String password) {
        User user = userRepository.findUserByUsername(username);
        if (user == null){
            System.out.println("登录失败 没有该用户");
            throw new AppException("登录失败 没有该用户", R.Code.usernameNotFound);
        }

        if (user.getDeleteAt() != null){
            System.out.println("登录失败 该用户已被禁用");
            throw new AppException("登录失败 该用户已被禁用", R.Code.usernameNotFound);
        }

        if (!user.getPassword().equals(password)) {
            System.out.println("密码错误");
            throw new AppException("密码错误", R.Code.passwordNotMatch);
        }

        // 创建 token
        JwtBuilder builder = Jwts.builder()
                .setSubject(username)
                .signWith(SignatureAlgorithm.HS256,"123456".getBytes());

        var jwt = builder.compact();




        //生成JWT
        return jwt;
    }

    public User checkJWT(String token) {
        Claims claims = Jwts.parser()
        .setSigningKey("123456".getBytes())
        .parseClaimsJws(token).getBody();

        String subject = claims.getSubject();

        User user = userRepository.findUserByUsername(subject);

        return user;
    }

    public void signup(String username, String password) {
        UserCreatePara para = new UserCreatePara();
        para.setUsername(username);
        para.setPassword(password);
        userServer.create(para);
    }
}
